from django.core.paginator import Paginator

from utils.redis import redis_conn
from users.models import *
from utils.token_utils import login_token
from .serializers import *

from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status

from django.http import HttpResponse
from django.db.models import Q
from django.db.models import F

from captcha.image import ImageCaptcha
import string
import random, logging
import json
from utils.ip_address.ip_info import CzIp


# 分页函数
def pag(self, userinfo, pag_size, pagination):
    paginator = Paginator(userinfo, pag_size)

    page = paginator.page(pagination)

    return page.object_list


# 图片验证码
class ImageView(APIView):

    def get(self, request, uuid):
        print("uuid>>>>>>>>>>", uuid, type(uuid))

        # 生成随机字符
        alpha_number = string.ascii_letters + string.digits
        img_code = "".join(random.sample(alpha_number, 4))
        print("image_code>>>>>>>>>>>>>>", img_code)

        # 生成图片验证码
        img_cap = ImageCaptcha()
        img_code_cap = img_cap.generate(img_code)
        print("img_code_cap>>>>>>>>>>>", img_code_cap)

        # 存储图片验证码
        key = "image_code:%s"%uuid
        red = redis_conn()
        red.set(key, img_code, ex=300)
        red.close()

        return HttpResponse(img_code_cap, content_type="image/png")


# 登录
class LoginView(APIView):

    # 获取ip
    def gain_ip(self, request):
        ip = ''
        try:
            # HTTP_X_FORWARDED_FOR: 浏览当前页面的用户计算机的网关.
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                # REMOTE_ADDR: 浏览当前页面的用户计算机的ip地址
                ip = request.META.get('REMOTE_ADDR')
        except Exception as e:
            logging.info("request user IP address failed. error msg:{}".format(e))
        return ip

    def post(self, request):
        try:
            # 获取前端传递的数据
            name = request.data.get("name")
            password = request.data.get("password")
            code = request.data.get("code")
            uuid = request.data.get("uuid")

            user = UserModel.objects.get(name=name)
            # 校验
            red = redis_conn()
            key = "image_code:%s"%uuid
            red_code = red.get(key)
            print("red_code, code>>>>>>>>>>", red_code, code)
            if red_code.decode().lower() != str(code).lower():
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg":"验证码不正确"})

            if not user:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "账号不存在"})

            if not user.password == password:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg":"密码错误"})

            if user.userstate == "2":
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg":"该用户已离职"})

            # 生成payload
            id = user.id
            payloads = {
                "id": user.id,
                "name": user.name,
            }
            ser = UserSer(user)

            ip = self.gain_ip(request)
            # 获取登陆的设备
            device = request.headers.get("User-Agent")
            # 获取登陆地址
            cz = CzIp()
            places = cz.get_addr_by_ip(ip)
            print(places)
            print("132222222222222222222222222222")
            LoginLogModel.objects.create(ip=ip,device=device,user_id=id,address=places)

            # 添加操作日志
            OperateModel.objects.create(user_id=user.id,action="登录",path='/login/')
            token = login_token(payloads)
            return Response({"code": status.HTTP_200_OK, "msg":"登陆成功", "token": token})
        except Exception as e:
            print("登陆的报错>>>>>>>>>>>", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 首页数据
class HomeView(ViewSet):

    # 获取生日
    def user_cunt(self, request):
        try:
            users = UserModel.objects.all()
            user_ser = UserSer(users, many=True)
            # print("获取到的数据user》》》》", user_ser.data)

            # 生成一个字典key值为1-12， value为0
            month_data_tow = {}
            for mouth in range(1, 13):
                if mouth == 1:
                    month_data_tow.setdefault("january", 0)
                if mouth == 2:
                    month_data_tow.setdefault("february", 0)
                if mouth == 3:
                    month_data_tow.setdefault("march", 0)
                if mouth == 4:
                    month_data_tow.setdefault("april", 0)
                if mouth == 5:
                    month_data_tow.setdefault("may", 0)
                if mouth == 6:
                    month_data_tow.setdefault("june", 0)
                if mouth == 7:
                    month_data_tow.setdefault("july", 0)
                if mouth == 8:
                    month_data_tow.setdefault("august", 0)
                if mouth == 9:
                    month_data_tow.setdefault("september", 0)
                if mouth == 10:
                    month_data_tow.setdefault("october", 0)
                if mouth == 11:
                    month_data_tow.setdefault("november", 0)
                if mouth == 12:
                    month_data_tow.setdefault("december", 0)
            print(month_data_tow)
            for user in user_ser.data:
            # print(user.get("birthday"))
                if 1 == int(user.get("birthday")):
                    month_data_tow["january"] += 1
                if int(user.get("birthday")) == 2:
                    month_data_tow["february"] += 1

                if int(user.get("birthday")) == 3:
                    month_data_tow["march"] += 1

                if int(user.get("birthday")) == 4:
                    month_data_tow["april"] += 1

                if int(user.get("birthday")) == 5:
                    month_data_tow["may"] += 1

                if int(user.get("birthday")) == 6:
                    month_data_tow["june"] += 1

                if int(user.get("birthday")) == 7:
                    month_data_tow["july"] += 1

                if int(user.get("birthday")) == 8:
                    month_data_tow["august"] += 1

                if int(user.get("birthday")) == 9:
                    month_data_tow["september"] += 1

                if int(user.get("birthday")) == 10:
                    month_data_tow["october"] += 1

                if int(user.get("birthday")) == 11:
                    month_data_tow["november"] += 1

                if int(user.get("birthday")) == 12:
                    month_data_tow["december"] += 1
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data": month_data_tow})
        except Exception as e:
            print("获取生日的报错信息",e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR})

    # 获取信息数量
    def use_empdats(self, request):
        try:
            user = UserModel.objects.all()
            user_ser = UserSer(user, many=True)

            number_data = {}
            for number in range(1, 7):
                if number == 1:
                    number_data.setdefault("count", 0)

                if number == 2:
                    number_data.setdefault("formal", 0)

                if number == 3:
                    number_data.setdefault("exercitation", 0)

                if number == 4:
                    number_data.setdefault("awaitrding", 0)

                if number == 5:
                    number_data.setdefault("awaitdimission", 0)

                if number == 6:
                    number_data.setdefault("awaitpositive", 0)

            for user in user_ser.data:
                number_data["count"] += 1
                if int(user.get("userstate")) == 3:
                    number_data["formal"] += 1

                if int(user.get("userstate")) == 0:
                    number_data["exercitation"] += 1

                if int(user.get("userstate")) == 2:
                    number_data["awaitrding"] += 1

                if int(user.get("userstate")) == 4:
                    number_data["awaitdimission"] += 1

                if int(user.get("userstate")) == 5:
                    number_data["awaitpositive"] += 1
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data": number_data})
        except Exception as e:
            print("获取信息错误》》》》》》》》》",e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 用户管理
class UserViews(ViewSet):

    # 获取全部用户
    def all_user(self, request):
        try:
            # 接收一页展示多少条数据
            pag_size = request.data.get("pag_size")
            # # 展示的页码
            pagination = request.data.get("pagination")

            user = UserModel.objects.all()
            user_ser = UserSer(user, many=True)
            # print("用户信息",user_ser.data)
            for user in user_ser.data:
                position_id = user.get("position")
                print("position_id", position_id)
                position = PositionModel.objects.filter(id=position_id)
                position_ser = PositionSer(position, many=True)
                for position in position_ser.data:
                    # print("职位信息",position)
                    # 合成信息
                    user["rank"] = position.get("rankname")
                    user["department"] = position.get("departmentname")
                    position_role= PositionRoleModel.objects.get(position_id=position.get("id"))
                    position_role_ser = PositionRoleSer(position_role)
                    user["role"] = position_role_ser.data.get("rolename")
            # print(user_ser.data)
            return Response({"code": status.HTTP_200_OK, "msg":"查询成功", "data": user_ser.data})
        except Exception as e:
            print("获取全部用户", e)
            return Response({"code":status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    # 添加用户
    def add_user(self,request):
        try:
            name = request.data.get("uname")
            account = request.data.get("username")
            mobile = request.data.get("mobile")
            password = request.data.get("password")
            role = request.data.get("rolename")
            position = request.data.get("position")
            rank = request.data.get("grade")
            department = request.data.get("department")
            print("接收到的数据", request.data)

            user_name = UserModel.objects.filter(name=name).count()
            if user_name !=0:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg":"用户名已存在"})
            user_mobile = UserModel.objects.filter(mobile=mobile).count()
            if user_mobile != 0:
                return Response({"code":status.HTTP_400_BAD_REQUEST, "msg":'手机号已存在'})
            user_account = UserModel.objects.filter(account=account).count()
            if user_account != 0:
                return Response({'code':status.HTTP_400_BAD_REQUEST, "msg":'账号已存在'})

            data = {
                "name":name,
                "mobile":mobile,
                "account":account,
                "rank": rank,
                "sex": "男",
                "position": position,
                "address": "河南",
                "password":password
            }
            ser = UserSer(data=data)
            if not ser.is_valid():
                return Response({"code":status.HTTP_400_BAD_REQUEST,"msg":ser.errors})
            position = PositionModel.objects.filter(department=department).count()
            if position != 0:
                position = PositionModel.objects.filter(department=department, rank=rank)
                position_ser = PositionSer(position, many=True)
                print(position_ser.data)
                for position in position_ser.data:
                    print("123456")
                    print(position)
                    UserModel.objects.create(name=name, account=account, password=password, mobile=mobile, rank_id=rank, position_id=position.get("id"), address="河南", sex="男")
                return Response({"code": status.HTTP_200_OK, "msg":'添加成功'})
        except Exception as e:
            print("用户添加失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":'服务器错误'})


    def searchs(self, request):
        name = request.data.get("name")
        mobile = request.data.get("mobile")
        position = request.data.get("position")

        try:
            positions = PositionModel.objects.all()

            if position:
                positions = positions.filter(name=position)
            user_list = []
            for j in positions:
                user_set = UserModel.objects.filter(position_id=j.id).all()

                if name:
                    user_set = user_set.filter(name=name)
                if mobile:
                    user_set = user_set.filter(mobile=mobile)
                ser = UserSer(user_set, many=True)
                user_set = json.loads(json.dumps(ser.data))
                for i in user_set:
                    rank = RankModel.objects.filter(id=j.rank_id).first()
                    dept = DepartmentModel.objects.filter(id=j.dept_id).first()
                    i['rank_id'] = rank.id
                    i["rank"] = rank.name
                    i["section_id"] = dept.id
                    i["section"] = dept.name
                user_list.extend(user_set)
            return Response({"code": status.HTTP_200_OK, "msg": "查询成功", "data": user_list})
        except Exception as e:
            print("查询失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "查询失败"})

# 用户管理tow
class UserViewsTow(ViewSet):

    # 获取单个用户
    def one_user(self, request, pk):
        try:
            user = UserModel.objects.filter(id=pk)
            user_ser = UserSer(user, many=True)
            # print("用户信息",user_ser.data)
            for user in user_ser.data:
                position_id = user.get("position")
                print("position_id", position_id)
                position = PositionModel.objects.filter(id=position_id)
                position_ser = PositionSer(position, many=True)
                for position in position_ser.data:
                    # print("职位信息",position)
                    # 合成信息
                    user["rank"] = position.get("rankname")
                    user["department"] = position.get("departmentname")
                    position_role= PositionRoleModel.objects.get(position_id=position.get("id"))
                    position_role_ser = PositionRoleSer(position_role)
                    user["role"] = position_role_ser.data.get("rolename")
            # print(user_ser.data)
            return Response({"code": status.HTTP_200_OK, "msg":"查询成功", "data": user_ser.data})
        except Exception as e:
            print("获取单个用户失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    # 修改单个用户
    def upd_user(self, request, pk):
        try:
            name = request.data.get("name")
            account = request.data.get("account")
            mobile = request.data.get("mobile")
            role = request.data.get("role")
            rank = request.data.get("rank")
            department = request.data.get("department")
            print("接收到的数据", request.data)

            user = UserModel.objects.filter(id=pk).first()
            data = UserSer(user)
            data = json.loads(json.dumps(data.data))
            data["password"] = user.password

            if name != None:
                data["name"] = name
            if account != None:
                data["account"] = name
            if mobile != None:
                data["mobile"] = mobile
            print("123456")
            ser = UserSer(instance=user, data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg":ser.errors})
            ser.save()
            return Response({"code":status.HTTP_200_OK, "msg":"修改成功"})
        except Exception as e:
            print("错误信息为", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})





















